package com.itlong.cloud.controller.sdkV1.cloud.intercom.app;

import com.itlong.cloud.POJO.DTO.property.IotCloudIntercomStateDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppTCPResultVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.common.network.ITCPServiceClient;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.LanguageTypeEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.enumerate.ecode_en.BaseErrorCodeEnumEN;
import com.itlong.cloud.equip.property.ICloudIntercomServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      云对讲SDK APP服务-开门 音视频切换控制器
 * </desc>
 *
 * @createDate 2018/11/21
 */
@Controller
@RequestMapping("/cloud/interface")
public class CloudTalkSDKAppOpenDoorAndVideoController {
    //日志记录对象
    private static final Logger LOG = LoggerFactory.getLogger(CloudTalkSDKAppOpenDoorAndVideoController.class);

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    ICloudIntercomServiceClient iCloudIntercomServiceClient;

    @Autowired
    ITCPServiceClient itcpServiceClient;

    @Autowired
    private RedisService redisService;

    @Value("${" + PlatformConstants.APP_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String APP_REQUEST_PARAMS_ENCRYPT_KEY;


    /**
     * <desc>
     *      SDK-app用户开门操作
     * <desc/>
     *
     * @param sipAccount sip帐号
     * @param message 指令相关信息
     * @return
     * @author Qiang.S
     * @createDate 2018-09-12
     */
    @ResponseBody
    @RequestMapping(value = "/app/appOpenDoor",method = RequestMethod.POST)
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_OPEN_DOOR_LOG_DESC)
    public MessageVO appOpenDoor(String language, String createTime, String sipAccount, String message, String sign) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MessageVO messageVO;
        try {
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("language",language);
            params.put("sipAccount",sipAccount);
            params.put("message",message);
            //验证签名
            if(!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                LOG.info("createTime:"+createTime+" language:"+language+" sipAccount:"+sipAccount+" message:"+message);
                return new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(sipAccount) || StringUtils.isEmpty(message)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            }
            //CloudTalkSDKServerUserCacheVO vo = iCloudTalkSDKServerUserServiceClient.retrieve(token,"1");
            //request.setAttribute("appId",vo.getAppid());
            //保存生成操作日志所需信息 详细描述和接口类别
            //request.setAttribute("remark",String.format("%s%s%s","设备sn：",sipAccount,"开门"));
            //request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
            String deviceUnique = iCloudIntercomServiceClient.getDeviceUniqueBySip(sipAccount);
            //iot不在线走tcp
            if (redisService.get(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY+deviceUnique) == null ||
                    !redisService.get(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY+deviceUnique).equals("2")) {
//                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),itcpServiceClient.sendMessage("",sipAccount,message,10));
                return new MessageVO(AppErrorCodeEnum.CLOUD_TALK_IS_NOT_ONLINE_ERROR.getErrorCode());
            } else {//iot在线
                iCloudIntercomServiceClient.iotOpenDoor("",sipAccount,message,"1");
                int count = 0;
                AppTCPResultVO appTCPResultVO = new AppTCPResultVO();
                appTCPResultVO.setDataFlag("1");
                while(count<10){
                    Thread.sleep(500);
                    IotCloudIntercomStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_INTERCOM_STATE_CACHE +
                            deviceUnique), IotCloudIntercomStateDTO.class);
                    if(dto != null && dto.getMsgCode() == 0){
                        appTCPResultVO.setDataFlag("0");
                        redisService.del(RedisConstant.REDIS_IOT_CLOUD_INTERCOM_STATE_CACHE +deviceUnique);
                        break;
                    }
                    count++;
                }
                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),appTCPResultVO);
            }
            return messageVO;
        } catch (Exception e) {
            throw new DataAccessException("【APP_云对讲SDK】开门异常", e);
        }
    }

    /**
     * <desc>
     *      SDK-app切换音视频
     * <desc/>
     *
     * @param videoState 0：音视频1音频
     * @param sipAccount sip帐号
     * @return
     * @author Qiang.S
     * @createDate 2018-09-12
     */
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_AUDIO_AND_VIDEO_LOG_DESC)
    @RequestMapping(value = "/app/switchVideo",method = RequestMethod.POST)
    @ResponseBody
    public MessageVO switchVideo(String videoState, String language, String createTime, String sipAccount, String sign) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MessageVO messageVO;
        try {
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("language",language);
            params.put("sipAccount",sipAccount);
            params.put("videoState",videoState);
            //验证签名
            if(!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(sipAccount) || StringUtils.isBlank(videoState)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            }
            //CloudTalkSDKServerUserCacheVO vo = iCloudTalkSDKServerUserServiceClient.retrieve(token,"1");
            //request.setAttribute("appId",vo.getAppid());
            //保存生成操作日志所需信息 详细描述和接口类别
            //request.setAttribute("remark",String.format("%s%s%s","设备sn：",sipAccount,"音视频切换"));
            //request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
            String deviceUnique = iCloudIntercomServiceClient.getDeviceUniqueBySip(sipAccount);
            //iot不在线走tcp
            if (redisService.get(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY+deviceUnique) == null ||
                    !redisService.get(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY+deviceUnique).equals("2")) {
//                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),itcpServiceClient.sendMessage("",sipAccount,videoState, 11));
                return new MessageVO(AppErrorCodeEnum.CLOUD_TALK_IS_NOT_ONLINE_ERROR.getErrorCode());
            }else {//iot在线
                iCloudIntercomServiceClient.switchVideo(sipAccount,videoState);
                int count = 0;
                AppTCPResultVO appTCPResultVO = new AppTCPResultVO();
                appTCPResultVO.setDataFlag("1");
                appTCPResultVO.setVideoState("");
                while(count<10){
                    Thread.sleep(500);
                    IotCloudIntercomStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_INTERCOM_STATE_CACHE +
                            deviceUnique),IotCloudIntercomStateDTO.class);
                    if(dto != null && dto.getMsgCode() == 0){
                        appTCPResultVO.setDataFlag("0");
                        appTCPResultVO.setVideoState(dto.getVideoState());
                        redisService.del(RedisConstant.REDIS_IOT_CLOUD_INTERCOM_STATE_CACHE +deviceUnique);
                        break;
                    }
                    count++;
                }
                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),appTCPResultVO);
            }
            return messageVO;
        } catch (Exception e) {
            throw new DataAccessException("【APP_云对讲SDK】切换音视频异常", e);
        }
    }
}
